package com.synergy.stockflow.filter;

import com.synergy.stockflow.service.JwtService;
import com.synergy.stockflow.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends BaseCorsRequestFilter {
    @Autowired
    private JwtService jwtService;
    @Autowired
    private UserService userService;


    @Override
    protected void doFilterCustom(HttpServletRequest request,
                                  HttpServletResponse response,
                                  FilterChain filterChain)
            throws ServletException, IOException {
        try {
            // 从 Header 提取 Token
            String token = jwtService.extractToken(request);

            // 验证 Token
            if (token != null && !jwtService.isExpired(token)) {
                // 获取jwt头名称，用于Spring Security安全验证
                String subject = jwtService.extractSubject(token);
                UserDetails userDetails = userService.loadUserByUsername(subject);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效 Token");
            return;
        }

        filterChain.doFilter(request, response);
    }

}
